<template>
    <div class="home">
        <we-header @showExtend="showExtend">微信</we-header>
        <!-- 顶部弹出框 -->
        <we-popup ref="upPopup" up>
           <down-list></down-list>
        </we-popup>
        <div class="chatWrapper">
          <!-- 置顶聊天框 -->
             <ul>
           <li v-for="(item,index) in indexList" :key="index" @click="toChatPage(item)" @touchstart="start($event,index)" @touchend="end" class="chatItem chatTop">
             <chat-list :data=item v-if="item.isTop"></chat-list>
           </li>
         </ul>
         <!-- 非置顶聊天框 -->
          <ul>
           <li v-for="(item,index) in indexList" :key="index" @click="toChatPage(item)" @touchstart="start($event,index)" @touchend="end" class="chatItem">
             <chat-list :data=item v-if="!item.isTop"></chat-list>
           </li>
         </ul>
          <!-- 聊天弹出框 -->
        <we-popup ref="chatPopup" :bodyWidth="120" :bodyHeight="130">
            <div class="chatBox-wrapper f-col">
                <div v-for="(item,index) in chatBox" :key="index" class="chatBox-item f-1" @click="boxEvent(item.event)">
                  {{item.title}}
                </div>
            </div>
        </we-popup>
        </div>
        <loading v-if="showLoading"></loading>
    </div>
</template>
<script>
import weHeader from './common/weHeader';
import chatList from './chat/chatList';
import wePopup from './common/wePopup';
import downList from './common/downList';
import loading from './common/loading';
import {Meteor} from 'meteor/meteor';
import { image, user,indexMsg, friends, messages,group,groupUser } from '../../api/collections/index';
export default {
    components:{
        weHeader,
        chatList,
        wePopup,
        downList,
        loading
    },
       meteor: {
    $subscribe: {
      'userInf': []
    },
    indexList(){
        const id = sessionStorage.getItem('user')
        let newArr = []
        let list = indexMsg.find({I_UserId:id}).fetch()
       if(list.length>0){
          let personList = list.filter(e => {return e.I_Type == 'person'})
          let groupList = list.filter(e => {return e.I_Type == 'group'})
          if(personList.length>0){
          personList.forEach(e => {
          let infWrapper1 = {}
          infWrapper1.noReadCount = e.I_noReadCount
          infWrapper1.isTop = e.I_isTop
          infWrapper1.otherId = e.I_OtherId
          infWrapper1.lastMsgId = e.I_LastMsgId
          infWrapper1.isGroup = false
         const friend = friends.findOne({F_UserID:id,F_FriendID:e.I_OtherId})
          if(friend){
            const userInf = user.findOne({_id:e.I_OtherId})
            if(userInf){
               infWrapper1.name = friend.F_beizhu?friend.F_beizhu:userInf.nickname
            }
            const avatar1 = image.findOne({_id:friend.F_FriendAvatarId})
            if(avatar1){
              infWrapper1.avatar = avatar1.base64
            }
          }
          const msg = messages.findOne({_id:e.I_LastMsgId})
          if(msg){
            switch(msg.M_MessagesType){
              case 'text':infWrapper1.lastMsg = msg.M_PostMessages;break;
              case 'face':infWrapper1.lastMsg = '[动画表情]';break;
              case 'image':infWrapper1.lastMsg = '[图片]';break;
              case 'packet':
                if(msg.M_PostMessages.isOpen == false){
                  infWrapper1.lastMsg = '[微信红包]'+msg.M_PostMessages.message
                }
                if(msg.M_FromUserID == this.id && msg.M_PostMessages.isOpen == true){
                  const user1 = friends.findOne({F_UserID:msg.M_FromUserID,F_FriendID:msg.M_ToUserID})
                  const user2 = user2.findOne({_id:msg.M_ToUserID})
                 if(user1&&user2){
                  infWrapper1.lastMsg = user1.F_beizhu?user1.F_beizhu:user2.nickname+'领取了你的红包'
                 }
                }
                if(msg.M_FromUserID !== this.id && msg.M_PostMessages.isOpen == true){
                  const user1 = friends.findOne({F_UserID:msg.M_FromUserID,F_FriendID:msg.M_ToUserID})
                  const user2 = user.findOne({_id:msg.M_ToUserID})
                   if(user1&&user2){
                  infWrapper1.lastMsg = '你领取了'+ user1.F_beizhu?user1.F_beizhu:user2.nickname+'的红包'
                 }
                }
                break;
                case 'sendPacket':
                  if(msg.M_PostMessages.acceptId!==this.id){
            const user1 = user.findOne({_id:msg.M_PostMessages.acceptId})
            const user2 = friends.findOne({F_UserID:this.id,F_FriendID:msg.M_PostMessages.acceptId})
            if(user1 && user2){
               infWrapper1.lastMsg = (user2.F_beizhu?user2.F_beizhu:user1.nickname)+'领取了你的红包'
            }
                  }
                  else{
            const user1 = user.findOne({_id:msg.M_PostMessages.fromId})
            const user2 = friends.findOne({F_UserID:this.id,F_FriendID:msg.M_PostMessages.fromId})
            if(user1 && user2){
               infWrapper1.lastMsg = '你领取了'+(user2.F_beizhu?user2.F_beizhu:user1.nickname)+'的红包'
            }
                  }
                  break;
              default:break;
            }
            infWrapper1.time = msg.M_Time
          }
          newArr.push(infWrapper1)
        })
        }
        if(groupList.length>0){
          groupList.forEach(e => {
            let infWrapper2 = {}
          infWrapper2.noReadCount = e.I_noReadCount
          infWrapper2.isTop = e.I_isTop
          infWrapper2.otherId = e.I_OtherId
          infWrapper2.lastMsgId = e.I_LastMsgId
          infWrapper2.isGroup = true
          const groupInf = group.findOne({_id:e.I_OtherId})
          const groupUserInf = groupUser.findOne({gid:e.I_OtherId,userId:id})
          if(groupInf){
            if(groupUserInf){
              infWrapper2.name = groupUserInf.groupRemark?groupUserInf.groupRemark:groupInf.g_name
            }
            else{
              infWrapper2.name = groupInf.g_name
            }
            const avatar2 = image.findOne({_id:groupInf.g_avatarId})
            if(avatar2){
              infWrapper2.avatar = avatar2.base64
            }
          }
            const msg2 = messages.findOne({_id:e.I_LastMsgId})
            if(msg2){
              const userInf = groupUser.findOne({userId:msg2.M_FromUserID})
              switch(msg2.M_MessagesType){
              case 'text':
                if(userInf){
                   infWrapper2.lastMsg = userInf.groupName+': '+msg2.M_PostMessages;
                }
                else{
                  const inf = user.findOne({_id:msg2.M_FromUserID})
                  if(inf){
                    infWrapper2.lastMsg = inf.nickname+': '+msg2.M_PostMessages;
                  }
                }
               break;
              case 'face':infWrapper2.lastMsg =userInf.groupName+': [动画表情]';break;
              case 'image':infWrapper2.lastMsg = userInf.groupName+': [图片]';break;
              case 'packet':infWrapper2.lastMsg = '[红包]你有红包未领取';break;
              case 'invite':
                let obj = msg2.M_PostMessages
                if(obj.inviteId == obj.inviteeId){
                  const user1 = user.findOne({_id:obj.inviteId})
                  if(user1){
                    infWrapper2.lastMsg = user1.nickname+'创建了群聊'
                  }
                }else{
                  const user1 = user.findOne({_id:obj.inviteId})
                  const user2 = user.findOne({_id:obj.inviteeId})
                  if(user1&&user2){
                    infWrapper2.lastMsg = '"'+user1.nickname+'"'+'邀请'+'"'+user2.nickname+'"'+'加入了群聊'
                  }
                }
                ;break;
              default:break;
            }
            infWrapper2.time = msg2.M_Time
            }
          else{
            infWrapper2.lastMsg = ''
            if(groupUserInf){
              infWrapper2.time = groupUserInf.add_time
            }
          }
          newArr.push(infWrapper2)
          })
        }
       }
        newArr.sort((item1,item2)=>{
          return item2.time-item1.time
        })
         
         newArr.forEach((e,i)=>{
           if(i!==newArr.length-1){
             e.noLine = false
           }
           else{
             e.noLine = true
           }
         })
        return newArr
    },
    },
    mounted(){
      this.showLoading = false;
    },
    data(){
        return{
          showLoading:true,
          // 聊天弹出框内容
          chatBox:[
            {
              title:'标为未读',
              event:'setReadStatus'
            },
             {
              title:'置顶聊天',
              event:'setTopChat'
            },
             {
              title:'删除该聊天',
              event:'delChat'
            }
          ],
          chatIndex:-1,
          id:sessionStorage.getItem('user')
        }
    },
    methods:{
        // 跳转到聊天详情页
        toChatPage(item){
            if(item.isGroup){
              this.$router.push('/chatGroupPage/'+item.otherId)
            }else{
              this.$router.push('/chatPage/'+item.otherId)
            }
        },
        // 长按事件
        start(e,index){
      clearTimeout(this.loop); //再次清空定时器，防止重复注册定时器
        let x=0
        let y=0
      this.loop = setTimeout(() => {
        if(e.changedTouches.length>0){
            x=e.changedTouches[0].clientX
            y=e.changedTouches[0].clientY
            }
            this.chatIndex=index
            let item = this.indexList[this.chatIndex]
            this.chatBox[0].title = item.noReadCount==0?'标为未读':'标为已读'
            this.chatBox[1].title=item.isTop?'取消置顶':'置顶聊天'
            this.$refs.chatPopup.show(x,y)
      },750);
    },
    end(){
      clearTimeout(this.loop); //清空定时器，防止重复注册定时器
    },
    showExtend(){
        this.$refs.upPopup.show()
    },
    // 长按弹出框点击事件
    boxEvent(e){
     switch(e){
       case 'setReadStatus':this.setReadStatus(); break;
       case 'setTopChat':this.setTopChat(); break;
       case 'delChat':this.delChat();break;
       default:break;
     }
     this.$refs.chatPopup.hide()
    },
    // 设置已读/未读
    setReadStatus(){
      const arr = this.indexList[this.chatIndex]
      const user = sessionStorage.getItem('user')
      if(arr.noReadCount==0){
        Meteor.call('message.isNoRead',arr.lastMsgId)
         Meteor.call('indexMsg.updateCountByone',{
          userId:user,
          otherId:arr.otherId
    })
      }
      else{
        Meteor.call('message.isReaded',{
        toID:user,
        fromID:arr.otherId
        })
        Meteor.call('indexMsg.updateCount',{
          userId:user,
          otherId:arr.otherId
    })
      }
    },
    // 设置是否置顶聊天
    setTopChat(){
      const arr = this.indexList[this.chatIndex]
      Meteor.call('indexMsg.updateTopStatus',{
        userId:sessionStorage.getItem('user'),
        otherId:arr.otherId,
        isTop:!arr.isTop
      })
    },
    // 删除聊天
    delChat(){
      const arr = this.indexList[this.chatIndex]
      Meteor.call('indexMsg.delete',{
         userId:sessionStorage.getItem('user'),
        otherId:arr.otherId
      })
    }
    }
}
</script>
<style scoped>
.home{
  background-color: #fff;
}
.chatWrapper{
    margin-top: 1.5rem;
    background-color: #fff;
}
.chatBox-wrapper{
  width: 5rem;
  height: 6rem;
  font-size: .6rem;
  background-color: #fff;
  border: 1px solid rgba(204,204,204,.5);
  box-sizing: border-box;
  box-shadow: 1px 1px 1px rgba(204,204,204,.5);
}
.chatBox-item{
  padding-left: .5rem;
  line-height: 40px;
}

.chatBox-item:active{
  background: rgba(0,0,0,.1);
}
.chatTop{
  background-color: #F7F7F7!important;
}
</style>